package com.seek.service.imp;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.seek.cache.CacheUtil;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.SysRoleDao;
import com.seek.inter.interdto.InterDtoUser;
import com.seek.model.entity.TSysRole;
import com.seek.service.SysRoleService;
import com.seek.util.BeanUtils;
import com.seek.util.CommonUtil;

@Repository("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<TSysRole> implements SysRoleService {

	@Autowired
	public void setDao(SysRoleDao sysRoleDao) {
		super.setDao(sysRoleDao);
	}
	public SysRoleDao getDao() {
		return (SysRoleDao) super.getDao();
	}
	
	public TSysRole save(JSONObject reqJson) throws Exception{
		TSysRole en = new TSysRole();
	
		en.setId(reqJson.getLong("roleId"));
		en.setCompanyId(reqJson.getLong("companyId"));
		en.setRoleName(reqJson.getString("roleName"));
		en.setIsAdmin(reqJson.getInteger("isAdmin"));
		en.setIsAgent(reqJson.getInteger("isAgent"));
		en.setRemark(reqJson.getString("remark"));
		
		String token = reqJson.getString("token");
		InterDtoUser user = CacheUtil.getLoginCache(token);
		if (en.getId() == null || en.getId()<1){
			en.setIsUsed(1);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(user.getId()));
			en.setModifyUserId(CommonUtil.getLongValue(user.getId()));
		}
		en.setModifyTime(new Date());
		return this.save(en);
	}
	
	// 重写保存方法 
	@SuppressWarnings({ "rawtypes"})
	public TSysRole save(TSysRole entity) throws Exception {
		if (CommonUtil.isEmpty(entity.getRoleName())){
			throw new Exception("角色名不能为空，请检查");
		}
		entity.setRoleName(entity.getRoleName().trim());
		
		// 如果是新增：
		if (entity.getId() == null || entity.getId() <= 0){
			return this.getDao().insert(entity);		
		}else{
			TSysRole old = this.getDao().get(entity.getId());
			// 如果原记录不存在或者已被删除，则提示
			if (old == null || old.getIsUsed() == 0){
				throw new Exception("您当前编辑的角色已被人删除，无法修改。");
			}
			// 如果是否为代理商角色修改，但原来角色已有操作员，则不允许修改
			if (old.getIsAgent().intValue() != entity.getIsAgent().intValue()){
				String sql = "select 1 from t_sys_user where company_id=? and role_id=?";
				List rows = this.getDao().findMapBySql(sql, new Object[]{entity.getCompanyId(), entity.getId()});
				if (rows != null && rows.size() > 0){
					throw new Exception("该角色下已维护有用户，不能修改“是否代理商”属性");
				}
			}
			BeanUtils.copyPropertiesExclude(entity, old, new String[]{"id","companyId","createUserId","createTime","isUsed"});
			return this.getDao().update(old);
		}
	}
}